#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <time.h>

#include "../include/thread.h"
#include "../include/mutex.h"

using namespace mix;

std::string buffer;
Mutex bufferLock;

void thread1_run() {
    for ( int i = 0; i < 10; ++i) {
        {
            Mutex::Guard g(bufferLock);

            buffer = "**************11111**************";
            printf( "in thread 1 buffer is %s\n", buffer.c_str());
        }
        Thread::sleep( rand() % 500);
    }
}

void thread2_run() {
    for ( int i = 0; i < 10;) {
        if ( bufferLock.tryLock()) {
            buffer = "##############2222###############";
            printf( "in thread 2 buffer is %s\n", buffer.c_str());
            bufferLock.unlock();
            ++i;
        }
        Thread::sleep( rand() % 500);
    }
}

void thread3_run() {
    for ( int i = 0; i < 10;) {
        if ( bufferLock.tryLock( i + 5)) {
            printf( "in thread 3 buffer is %s\n", buffer.c_str());
            bufferLock.unlock();
            ++i;
        }
        Thread::sleep( rand() % 500);
    }
}


int main() {
    time_t tm;
    time( &tm);
    srand( (int)tm);

    Thread t1( thread1_run);
    Thread t2( thread2_run);
    Thread t3( thread3_run);

    t1.start();
    t2.start();
    t3.start();

    t1.join();
    t2.join();
    t3.join();

    return 0;
}
